#include "dicomimportor.h"
#include "ui_dicomimportor.h"
#include "importthread.h"

#include <QDir>
#include <QFileDialog>
#include <QSettings>

#define OPEN_SRC_DIR "OPENSRCDIR"
#define OPEN_DEST_FILE "OPENDESTFILE"

DicomImportor::DicomImportor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DicomImportor)
{
    ui->setupUi(this);
}

DicomImportor::~DicomImportor()
{
    delete ui;
}

void DicomImportor::on_srcSelectBtn_clicked()
{
    QSettings s;
    QString p = s.value(OPEN_SRC_DIR, ".").toString();
    p = QFileDialog::getExistingDirectory(this, tr("Open Source Directory"), p);
    if (!p.isEmpty()) {
        s.setValue(OPEN_SRC_DIR, p);
        ui->srcPathEdit->setText(p);
    }
}

void DicomImportor::on_destSelectBtn_clicked()
{
    QSettings s;
    QString f = s.value(OPEN_DEST_FILE, ".").toString();
    f = QFileDialog::getOpenFileName(this, tr("SQLite Databae File"), f);
    if (!f.isEmpty()) {
        s.setValue(OPEN_DEST_FILE, f);
        ui->destPathEdit->setText(f);
    }
}

void DicomImportor::on_startBtn_clicked()
{
    ImportThread *t = new ImportThread(ui->srcPathEdit->text(), ui->destPathEdit->text());
    connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
    connect(t, SIGNAL(finished()), this, SLOT(onImportFinished()));
    connect(t, SIGNAL(totalFiles(int)), this, SLOT(onTotalFiles(int)));
    connect(t, SIGNAL(resultReady(bool,QString)), this, SLOT(onResultReady(bool,QString)));
    totalCnt = 100;
    okCnt = 0;
    ui->progressBar->setMinimum(0);
    ui->progressBar->setMaximum(totalCnt);
    ui->startBtn->setEnabled(false);
    t->start();
}

void DicomImportor::onResultReady(bool ok, const QString &msg)
{
    okCnt += ok?1:0;
    ui->progressBar->setValue(ui->progressBar->value()+1);
    ui->textBrowser->append(msg);
}

void DicomImportor::onImportFinished()
{
    ui->progressBar->setValue(totalCnt);
    ui->startBtn->setEnabled(true);

    ui->textBrowser->append(tr("total: %1, success: %2.").arg(totalCnt).arg(okCnt));
}

void DicomImportor::onTotalFiles(int count)
{
    totalCnt = count;
    ui->progressBar->setMaximum(totalCnt);
}
